import request from '@/utils/request';

import mz from "@/api/helpFunc/mz.json";
import zzmm from "@/api/helpFunc/zzmm.json";


export let isSameMonth = function (inDate, andDate) { // 判断是否是当月的日期
    var nowDate = new Date(andDate);
    return ((nowDate.getFullYear() == inDate.getFullYear()) &&
        (nowDate.getMonth() == inDate.getMonth()));
}

export function getHoliday(year = "") {
    return request({
        url: "https://timor.tech/api/holiday/year/" + year
    });
}

//民族
export const mz_list = [...mz];

//政治面貌
export const zzmm_list = [...zzmm];

//血型
export const xx_list = [
    "A型", "B型", "AB型", "O型"
];

//校验邮政编码
export function isValidPostalCode(code) {
    const regex = /^[1-9]\d{5}$/;
    return regex.test(code);
}


//判断是不是正整数
export function isPositiveInteger(value) {
    return Number.isInteger(value) && value > 0;
}

//判断文件是不是图片
export function boolImg(file) {
    let img = file.name.substring(file.name.lastIndexOf('.') + 1)
    const suffix = img === 'jpg';
    const suffix2 = img === 'png';
    const suffix3 = img === 'jpeg';
    const suffix4 = img === 'bmp';
    const isLt1M = file.size / 1024 / 1024 < 5;
    if (!suffix && !suffix2 && !suffix3 && !suffix4) {
        alert("只能上传图片！");
        return false;
    }
    // 可以限制图片的大小
    if (!isLt1M) {
        alert('上传图片大小不能超过 5MB!');
        return false;
    }
    return suffix || suffix2 || suffix3 || suffix4;
}


export function CheckImgExists(imgurl) {
    var ImgObj = new Image(); //判断图片是否存在  
    ImgObj.src = imgurl;
    //没有图片，则返回-1  
    if (ImgObj.fileSize > 0 || (ImgObj.width > 0 && ImgObj.height > 0)) {
        return true;
    } else {
        return false;
    }
}



export let uniqueBy = (arr, key) => {
    const seen = new Set();
    return arr.filter((item) => {
        const k = item[key];
        return seen.has(k) ? false : seen.add(k);
    });
};

export function getChineseKey(key) {
    return '"' + key + '"';
}

export function getImg(img) {
    return (img == "" || img == null) ? require("@/assets/images/profile.jpg") : process.env.VUE_APP_BASE_API + img;
}

//分组
export const groupBy = (list, fn) => {
    const groups = {};
    list.forEach(function (o) {
        const group = JSON.stringify(fn(o));
        groups[group] = groups[group] || [];
        groups[group].push(o);
    });
    // return Object.keys(groups).map(function (group) {
    //     return groups[group];
    // });
    return groups;
}

export function fullLoading(vm) {
    let loading = vm.$loading({
        lock: true,
        text: '等待数据加载',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
    });

    setTimeout(() => {
        loading.close(); // 关闭Loading
    }, 60000);
    return loading;
}


export function dbfToJson(data) {
    let fields = data._fields;
    data.map((v, i) => {
        fields.map(x => {
            console.log(v[x.name])
        })
    });
}


export function isNumber(str) {
    return !isNaN(parseFloat(str)) && isFinite(str);
}


//判断是否为空
export function isEmpty(obj) {
    if (obj == null || obj == "" || obj == undefined) {
        return true;
    } else {
        return false;
    }
}

export function download(src) {
    return request({
        url: "/common/download/resource?resource=" + src,
        method: "get",
    });
}

export function getImageBase64(blob) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(blob);
        reader.onload = () => {
            const base64 = reader.result;
            resolve(base64);
        }
        reader.onerror = error => reject(error);
    });
}


export function getBase64(file) {  //把文件转成base64编码
    return new Promise(function (resolve, reject) {
        let reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function () {
            imgResult = reader.result;
        };
        reader.onerror = function (error) {
            reject(error);
        };
        reader.onloadend = function () {
            resolve(imgResult);
        }
    })
};

//将base64转换为blob
export function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
}
//下载方法
export function downloadFile(url, name = "附件") {
    var a = document.createElement("a");
    a.setAttribute("href", url);
    a.setAttribute("download", name);
    a.setAttribute("target", "_blank");
    let clickEvent = document.createEvent("MouseEvents");
    clickEvent.initEvent("click", true, true);
    a.dispatchEvent(clickEvent);
}

export function downloadFileByBase64(base64, name) {
    var myBlob = dataURLtoBlob(base64);
    var myUrl = URL.createObjectURL(myBlob);
    downloadFile(myUrl, name);
}

export function downloadFileByBlob(blob, name) {
    var myUrl = URL.createObjectURL(blob);
    downloadFile(myUrl, name);
}


//获取审核状态
export function getProcessState(state) {
    switch (state) {
        case 0:
            return "待审核";
        case 1:
            return "一级审核未通过";
        case 2:
            return "一级审核通过";
        case 3:
            return "二级审核未通过";
        case 4:
            return "二级审核通过";
        case 5:
            return "公示中";
        case 6:
            return "通过";
    }
}

// exceldown.js
import XLSX from "xlsx";
import XLSX2 from "xlsx-style";
// 生成excel的配置
export function workbook2blob(workbook) {
    // 生成excel的配置项
    var wopts = {
        // 要生成的文件类型
        bookType: "xlsx",
        // // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
        bookSST: false,
        type: "binary"
    };
    var wbout = XLSX.write(workbook, wopts);
    // 将字符串转ArrayBuffer
    function s2ab(s) {
        var buf = new ArrayBuffer(s.length);
        var view = new Uint8Array(buf);
        for (var i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
        return buf;
    }
    let buf = s2ab(wbout);
    var blob = new Blob([buf], {
        type: "application/octet-stream"
    });
    return blob;
}

export function workbook2blobStyle(workbook) {
    // 生成excel的配置项
    var wopts = {
        // 要生成的文件类型
        bookType: "xlsx",
        // // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
        bookSST: false,
        type: "binary"
    };
    var wbout = XLSX2.write(workbook, wopts);
    // 将字符串转ArrayBuffer
    function s2ab(s) {
        var buf = new ArrayBuffer(s.length);
        var view = new Uint8Array(buf);
        for (var i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
        return buf;
    }
    let buf = s2ab(wbout);
    var blob = new Blob([buf], {
        type: "application/octet-stream"
    });
    return blob;
}

// 将blob对象 创建bloburl,然后用a标签实现弹出下载框
export function openDownloadDialog(blob, fileName) {
    if (typeof blob === "object" && blob instanceof Blob) {
        blob = URL.createObjectURL(blob); // 创建blob地址
    }
    var aLink = document.createElement("a");
    aLink.href = blob;
    // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，有时候 file:///模式下不会生效
    aLink.download = fileName || "";
    var event;
    if (window.MouseEvent) event = new MouseEvent("click");
    //   移动端
    else {
        event = document.createEvent("MouseEvents");
        event.initMouseEvent(
            "click",
            true,
            false,
            window,
            0,
            0,
            0,
            0,
            0,
            false,
            false,
            false,
            false,
            0,
            null
        );
    }
    aLink.dispatchEvent(event);
}

//解析excel
export function file2Xce(file) {
    return new Promise(function (resolve, reject) {
        const reader = new FileReader();
        reader.onload = function (e) {
            const data = e.target.result;
            this.wb = XLSX.read(data, {
                type: "binary"
            });
            const result = [];
            this.wb.SheetNames.forEach(sheetName => {
                console.log(sheetName);
                result.push({
                    sheetName: sheetName,
                    sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName])
                });
            });
            resolve(result);
        };
        reader.readAsBinaryString(file.raw);
        // reader.readAsBinaryString(file) // 传统input方法
    });
}